package com.eryos.android.cigarettecounter.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.util.Log;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class DataExporter extends IOStream {

    private OutputStream os;
    private OutputStreamWriter osw;

    /**
     * Default constructor.
     * 
     * @param filenameArg
     *            filename to create.
     */
    public DataExporter(final String filenameArg) {
        Log.d("CigaretteCounter", getClass().getSimpleName() + " : new DataExporter()");

        this.setExternalFilename(filenameArg);
    }

    /**
     * Open a stream.
     * 
     * @return true if the stream is correctly opened.
     * @throws IOException
     *             in case of error
     */
    public boolean openStream() throws IOException {
        Log.d("CigaretteCounter", getClass().getSimpleName() + " : openStream ");

        if (this.openStream(TYPE.WRITE)) {

            os = new FileOutputStream(getOutputFile());
            osw = new OutputStreamWriter(os);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Write data to XML file stored in /sdcard/downloads directory.
     * 
     * @param data
     *            to write
     * @throws IOException
     *             in case of error
     */
    public void writeDataToExternalFile(final String data) throws IOException {
        osw.write(data);
    }

    /**
     * Write data to XML file stored in /sdcard/downloads directory.
     * 
     * @param data
     *            to write
     * @throws IOException
     *             in case of error
     */
    public void writeDataToExternalFile(final byte[] data) throws IOException {
        os.write(data);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void closeStream() throws IOException {
        Log.d("CigaretteCounter", getClass().getSimpleName() + " : closeStream");

        osw.flush();
        osw.close();
        os.flush();
        os.close();
    }

}
